var dotenv = require('dotenv').config();
/**
 * This the main entry file for the app.
 */

var Express = require('express'),
    BodyParser = require('body-parser'),
    Passport = require('passport'),
    Mongoose = require('mongoose'),
    Morgan = require('morgan'),
    JWT = require('jsonwebtoken'),
    secrets = require('./config/secrets'),
    apiHandler = require('./services/api-handler'),
    appConfig = require('./config/config'),
    authToken = require('./models/auth-token'),
    logger = require('./models/logger'),
    cors = require('cors');

var option = {
    server: {
        socketOptions: {
            keepAlive: 300000,
            connectTimeoutMS: 30000
        }
    },
    replset: {
        socketOptions: {
            keepAlive: 300000,
            connectTimeoutMS: 30000
        }
    },
    useMongoClient: true
};

// Setup database
Mongoose.Promise = global.Promise;

Mongoose.connect('mongodb://' + process.env.DB_HOST + '/' + process.env.DB_NAME, {useMongoClient: true});
Mongoose.connection;

// Init App
var App = Express();

// Cross origin
App.use(cors());

App.use(process.env.PROFILE_UPLOAD, Express.static('profileUploads'));

// To allow browser hit the url and download file
App.use(process.env.CSV_UPLOAD, Express.static('csv'));

// BodyParser middleware
// Create application/json parser
App.use(BodyParser.json({ limit: '50mb' })); // Set request size

// create application/x-www-form-urlencoded parser
App.use(BodyParser.urlencoded({ limit: '50mb', extended: true }));


// Passport init
App.use(Passport.initialize());
App.use(Passport.session());

// Creates server logs
App.use(Morgan('dev'));

// Token Interceptor
App.use(function (req, res, next) {
    var excludedRoutes = appConfig.excludedRoutes, token;

    if (excludedRoutes.indexOf(req.path) === -1) {
        token = req.headers.token || req.body.token || req.headers['x-access-token'];
        if (token) {
            authToken.getUserByToken(token, function (err, tokenUser) {
                if (err || !tokenUser) {
                    apiHandler.setErrorResponse('TOKEN_EXPIRED', res);
                } else {
                    JWT.verify(token, secrets.jwtSecret, function (err, decoded) {
                        if (err) {
                            apiHandler.setErrorResponse('INVALID_TOKEN', res);
                        } else {
                            req.decoded = decoded;
                            req.user = tokenUser.user;
                            next();
                        }
                    });
                }
            });
        } else {
            apiHandler.setErrorResponse('NO_TOKEN', res);
        }
    } else {
        next();
    }
});

process.on('uncaughtException', function (exception) {
    console.log('---------------------------------uncaughtException--------------------------------'); 
    console.log(exception);
    var errorLog = new logger({
        details: err,
        activity: 'uncaughtException'
    });
    errorLog.save();
});

// Use the custom routes
require('./routes/index')(App);

// Set port
App.set('port', (process.env.PORT));
App.set('host', (process.env.HOST));

App.listen(App.get('port'), function () {
    console.log('Server started at ' + App.get('host') + ':' + App.get('port'));
});
